package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.util.*;

import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInGetDetailsVo;
import com.zzyl.serve.DTO.CheckInDTO;
import com.zzyl.serve.domain.NursingLevel;
import com.zzyl.serve.mapper.NursingLevelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * 入住Service业务层处理
 * 
 * @author SpringBoos
 * @date 2024-11-18
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Resource
    ElderMapper elderMapper;
    @Resource
    CheckInConfigMapper checkInConfigMapper;
    @Resource
    BedMapper bedMapper;
    @Resource
    ContractMapper contractMapper;
    @Resource
    NursingLevelMapper nursingLevelMapper;
    @Resource
    RoomMapper roomMapper;
    @Resource
    FloorMapper floorMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        List<CheckIn> checkIns = checkInMapper.selectCheckInList(checkIn);
        // 包含用户的敏感信息 进行数据脱敏 (hutool工具包)
//        checkIns = checkIns.stream().map(a -> {
//            CheckIn in = new CheckIn(); //
//            BeanUtils.copyProperties(a, in);
//            DesensitizedUtil.idCardNum(in.getIdCardNo(), 3, 2);
//            return in;
//        }).collect(Collectors.toList());
        return checkIns;
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int apply(CheckInDTO checkInDTO) {
        CheckInDTO.CheckInConfigDto checkInConfigDto = checkInDTO.getCheckInConfigDto();

        // 查询判断老人是否已经入住
        List<Elder> elders = elderMapper.selectList(Wrappers.lambdaQuery(Elder.class)
                .eq(Elder::getIdCardNo, checkInDTO
                        .getCheckInElderDto().getIdCardNo()));
        if(ObjectUtils.isNotEmpty(elders)){
             throw new RuntimeException("老人已经入住");
        }
        // 修改床位表
        Bed bed = new Bed();
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);
        //新增老人信息
        CheckInDTO.CheckInElderDto checkInElderDto = checkInDTO.getCheckInElderDto();
        Elder elder = new Elder();
       BeanUtils.copyProperties(checkInElderDto, elder);
       elder.setBedNumber(checkInConfigDto.getCode());
        elder.setBedId(checkInConfigDto.getBedId());
        elder.setSex(Long.valueOf(checkInElderDto.getSex()));
        elderMapper.insert(elder);
        //新增合同表
        CheckInDTO.CheckInContractDto checkInContractDto = checkInDTO.getCheckInContractDto();
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto,contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setSignDate(checkInContractDto.getSignDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setStatus(0L);
        contract.setContractNumber(UUID.randomUUID().toString());
        // 生成合同编号
       contractMapper.insertContract(contract);
        //插入入住表
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(checkInConfigDto,checkIn);
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setElderName(elder.getName());
        checkIn.setBedNumber(checkInConfigDto.getCode());
        List<CheckInDTO.ElderFamilyDto> elderFamilyDtoList = checkInDTO.getElderFamilyDtoList();
        checkIn.setRemark(JSONUtil.toJsonStr(elderFamilyDtoList));
        checkInMapper.insertCheckIn(checkIn);
        //插入入住配置表
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
        return 1;
    }

    @Override
    public CheckInGetDetailsVo getDetail(Long id) {


        //查询老人表 并且返回数据
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        // 查询合同配置表
        CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigByCheckInId(id);
        // 查询老人表
        Elder elders = elderMapper.selectElderById(checkIn.getElderId());
        CheckInGetDetailsVo.CheckInElderVO checkInElderVO = new CheckInGetDetailsVo.CheckInElderVO();
        checkInElderVO.setName(checkIn.getElderName());
        checkInElderVO.setIdCardNo(checkIn.getIdCardNo());
        checkInElderVO.setBirthday(elders.getBirthday());
         //计算老人的年龄
        String birthByIdCard = IdcardUtil.getBirthByIdCard(checkIn.getIdCardNo());
        int i = DateUtil.ageOfNow(DateUtil.parse(birthByIdCard, "yyyyMMdd"));
        checkInElderVO.setAge(i);
        checkInElderVO.setSex(Math.toIntExact(elders.getSex()));
        checkInElderVO.setPhone(elders.getPhone());
        checkInElderVO.setAddress(elders.getAddress());
        checkInElderVO.setImage(elders.getImage());
        checkInElderVO.setIdCardPortraitImg(elders.getIdCardPortraitImg());
        checkInElderVO.setIdCardNationalEmblemImg(elders.getIdCardNationalEmblemImg());
        //查询老人家属
        String remark = checkIn.getRemark();
        //把一个JSON格式的字符串转换成集合 给家属信息
        List<CheckInGetDetailsVo.ElderFamilyVO> list = JSONUtil.toList(remark, CheckInGetDetailsVo.ElderFamilyVO.class);
//        CheckInGetDetailsVo checkInGetDetailsVo = new CheckInGetDetailsVo();
//        checkInGetDetailsVo.setElderFamilyVoList(list);
        // 返回入住配置表
        CheckInGetDetailsVo.CheckInConfigVO checkInConfigVO = new CheckInGetDetailsVo.CheckInConfigVO();
        BeanUtils.copyProperties(checkIn,checkInConfigVO);
        checkInConfigVO.setGovernmentSubsidy(checkInConfig.getGovernmentSubsidy());
        checkInConfigVO.setOtherFees(checkInConfig.getOtherFees());
        checkInConfigVO.setInsurancePayment(checkInConfig.getInsurancePayment());
        checkInConfigVO.setDeposit(checkInConfig.getBedFee());
        checkInConfigVO.setFeeStartDate(checkInConfig.getFeeStartDate());
        checkInConfigVO.setFeeEndDate(checkInConfig.getFeeEndDate());
        checkInConfigVO.setNursingLevelId(checkInConfig.getNursingLevelId());
        checkInConfigVO.setBedFee(checkInConfig.getBedFee());


        Bed bed = bedMapper.selectBedById(elders.getBedId());
        Room room = roomMapper.selectRoomById(bed.getRoomId());

        Floor floor = floorMapper.selectFloorById(room.getFloorId());
        String code = room.getCode();
        String bedNumber = floor.getCode()+"/"+code+"/"+bed.getBedNumber();
        String[] bed1 = {bedNumber};
        checkInConfigVO.setBed(bed1);

        Contract contract = contractMapper.selectContractByElderId(checkIn.getElderId());
        CheckInGetDetailsVo.ContractVO contractVO = new CheckInGetDetailsVo.ContractVO();
        contractVO.setContractName(contract.getContractName());
        contractVO.setThirdPartyName(contract.getThirdPartyName());
        contractVO.setThirdPartyPhone(contract.getThirdPartyPhone());
        contractVO.setAgreementPath(contract.getAgreementPath());
        contractVO.setSignDate(contract.getSignDate());
        CheckInGetDetailsVo checkInGetDetailsVo1 = new CheckInGetDetailsVo();
        checkInGetDetailsVo1.setCheckInElderVo(checkInElderVO);
        checkInGetDetailsVo1.setCheckInConfigVo(checkInConfigVO);
        checkInGetDetailsVo1.setContractVo(contractVO);
        checkInGetDetailsVo1.setElderFamilyVoList(list);
        return checkInGetDetailsVo1;

    }
}
